package servlet.DeviceServlet;

import dao.DeviceDao;
import entity.DeviceBean;
import entity.PageBean;
import javax.servlet.annotation.WebServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/deviceList")
public class DeviceListServlet extends HttpServlet {
    public DeviceListServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = "";
        String number = "";
        String type = "";
        String vendor = "";
        String date = "";
        if (req.getParameter("name") != null) name = req.getParameter("name");
        if (req.getParameter("number") != null) number = req.getParameter("number");
        if (req.getParameter("type") != null) type = req.getParameter("type");
        if (req.getParameter("vendor") != null) vendor = req.getParameter("vendor");
        if (req.getParameter("date") != null) date = req.getParameter("date");
        int pageSize = 6;

        DeviceDao dao = new DeviceDao();
        int pageCount = dao.findPageCount(name, number, type, vendor, date, pageSize);
        int curpage = 1;
        if (req.getParameter("page") != null) {
            String pg = req.getParameter("page");
            curpage = Integer.parseInt(pg);
        }
        int al = 0; //al为-1时表示上一页，为1时表示下一页，默认为0
        if (req.getParameter("alterPage") != null) {
            String alpg = req.getParameter("alterPage");
            al = Integer.parseInt(alpg);
        }

        PageBean pageBean = new PageBean(curpage, al, pageCount);
        List<DeviceBean> list = dao.listFindDevice(name, number, type, vendor, date, pageBean.getCurPage(), pageSize);

        req.setAttribute("list", list);
        req.setAttribute("pageBean", pageBean);
        req.getRequestDispatcher("device_list.jsp").forward(req, resp);
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
